package com.rickpan.controller;

import com.rickpan.common.Result;
import com.rickpan.entity.Favorite;
import com.rickpan.service.FavoriteService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏管理Controller
 * 
 * @author RickPan Team
 * @since 2024-01-06
 */
@Slf4j
@RestController
@RequestMapping("/api/favorites")
@Tag(name = "收藏管理", description = "文件收藏相关接口")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    /**
     * 添加收藏
     */
    @PostMapping
    @Operation(summary = "添加收藏", description = "收藏指定文件")
    public Result<Favorite> addFavorite(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            Long fileId = Long.valueOf(request.get("fileId").toString());
            String itemType = (String) request.getOrDefault("itemType", "file");
            String category = (String) request.get("category");
            String notes = (String) request.get("notes");

            Favorite favorite = favoriteService.addFavorite(userId, fileId, itemType, category, notes);
            return Result.success("收藏成功", favorite);
        } catch (Exception e) {
            log.error("添加收藏失败", e);
            return Result.error("收藏失败: " + e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/{fileId}")
    @Operation(summary = "取消收藏", description = "取消收藏指定文件")
    public Result<String> removeFavorite(@PathVariable Long fileId, HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            boolean success = favoriteService.removeFavorite(userId, fileId);
            if (success) {
                return Result.success("取消收藏成功");
            } else {
                return Result.error("文件未收藏");
            }
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.error("取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 更新收藏信息
     */
    @PutMapping("/{favoriteId}")
    @Operation(summary = "更新收藏信息", description = "更新收藏的分类和备注")
    public Result<Favorite> updateFavorite(@PathVariable Long favoriteId, 
                                          @RequestBody Map<String, Object> request, 
                                          HttpServletRequest httpRequest) {
        try {
            String category = (String) request.get("category");
            String notes = (String) request.get("notes");

            Favorite favorite = favoriteService.updateFavorite(favoriteId, category, notes);
            return Result.success("更新成功", favorite);
        } catch (Exception e) {
            log.error("更新收藏信息失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取收藏列表
     */
    @GetMapping
    @Operation(summary = "获取收藏列表", description = "分页获取用户收藏的文件列表")
    public Result<Map<String, Object>> getFavorites(@RequestParam(required = false) String category,
                                                   @RequestParam(required = false) String search,
                                                   @RequestParam(defaultValue = "1") Integer page,
                                                   @RequestParam(defaultValue = "20") Integer size,
                                                   HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            Page<Favorite> favorites = favoriteService.getFavoritesByUser(userId, category, search, page, size);

            // 转换为前端期望的格式
            Map<String, Object> result = new HashMap<>();
            result.put("records", favorites.getContent());
            result.put("total", favorites.getTotalElements());
            result.put("current", favorites.getNumber() + 1); // Spring Data从0开始，前端从1开始
            result.put("size", favorites.getSize());
            result.put("pages", favorites.getTotalPages());

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取收藏列表失败", e);
            return Result.error("获取收藏列表失败: " + e.getMessage());
        }
    }

    /**
     * 检查收藏状态
     */
    @GetMapping("/check/{fileId}")
    @Operation(summary = "检查收藏状态", description = "检查指定文件是否已收藏")
    public Result<Boolean> checkFavorite(@PathVariable Long fileId, HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            boolean isFavorited = favoriteService.isFavorited(userId, fileId);
            return Result.success(isFavorited);
        } catch (Exception e) {
            log.error("检查收藏状态失败", e);
            return Result.error("检查收藏状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近收藏
     */
    @GetMapping("/recent")
    @Operation(summary = "获取最近收藏", description = "获取最近收藏的文件列表")
    public Result<List<Favorite>> getRecentFavorites(@RequestParam(defaultValue = "10") Integer limit,
                                                     HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<Favorite> favorites = favoriteService.getRecentFavorites(userId, limit);
            return Result.success(favorites);
        } catch (Exception e) {
            log.error("获取最近收藏失败", e);
            return Result.error("获取最近收藏失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类统计
     */
    @GetMapping("/categories")
    @Operation(summary = "获取分类统计", description = "获取收藏文件的分类统计信息")
    public Result<List<FavoriteService.CategoryStat>> getCategoryStats(HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            List<FavoriteService.CategoryStat> stats = favoriteService.getCategoryStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取分类统计失败", e);
            return Result.error("获取分类统计失败: " + e.getMessage());
        }
    }

    /**
     * 批量收藏
     */
    @PostMapping("/batch")
    @Operation(summary = "批量收藏", description = "批量收藏多个文件")
    public Result<Integer> batchAddFavorites(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            @SuppressWarnings("unchecked")
            List<Long> fileIds = (List<Long>) request.get("fileIds");
            String category = (String) request.get("category");

            int successCount = favoriteService.batchAddFavorites(userId, fileIds, category);
            return Result.success("批量收藏完成", successCount);
        } catch (Exception e) {
            log.error("批量收藏失败", e);
            return Result.error("批量收藏失败: " + e.getMessage());
        }
    }

    /**
     * 批量取消收藏
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量取消收藏", description = "批量取消收藏多个文件")
    public Result<Integer> batchRemoveFavorites(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            @SuppressWarnings("unchecked")
            List<Long> fileIds = (List<Long>) request.get("fileIds");

            int successCount = favoriteService.batchRemoveFavorites(userId, fileIds);
            return Result.success("批量取消收藏完成", successCount);
        } catch (Exception e) {
            log.error("批量取消收藏失败", e);
            return Result.error("批量取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件类型统计
     */
    @GetMapping("/file-types")
    @Operation(summary = "获取文件类型统计", description = "获取收藏文件的类型统计信息")
    public Result<List<Map<String, Object>>> getFileTypeStats(HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            // TODO: 实现真实的文件类型统计逻辑
            List<Map<String, Object>> stats = new ArrayList<>();

            // 返回模拟数据
            Map<String, Object> stat1 = new HashMap<>();
            stat1.put("fileType", "image");
            stat1.put("typeName", "图片");
            stat1.put("count", 15);
            stat1.put("totalSize", 52428800L); // 50MB
            stats.add(stat1);

            Map<String, Object> stat2 = new HashMap<>();
            stat2.put("fileType", "document");
            stat2.put("typeName", "文档");
            stat2.put("count", 8);
            stat2.put("totalSize", 10485760L); // 10MB
            stats.add(stat2);

            Map<String, Object> stat3 = new HashMap<>();
            stat3.put("fileType", "video");
            stat3.put("typeName", "视频");
            stat3.put("count", 3);
            stat3.put("totalSize", 104857600L); // 100MB
            stats.add(stat3);

            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取文件类型统计失败", e);
            return Result.error("获取文件类型统计失败: " + e.getMessage());
        }
    }
}
